package com.speechb.common.html;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2019/8/1 21:47
 */
public class HtmlUtil {
  private static final  Pattern IMG_SPLIT_PATTERN = Pattern.compile("<img.*?src=[\\\"|'](.*?)[\\\"|'].*?>");

    /**
     * @param targetStr 要处理的字符串
     * @description 切割字符串，将文本和img标签碎片化，如"ab<img>cd"转换为"ab"、"<img>"、"cd"
     */
    public static List<String> splitByImgTag(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        Matcher matcher = IMG_SPLIT_PATTERN.matcher(targetStr);
        int lastIndex = 0;
        while (matcher.find()) {
            if (matcher.start() > lastIndex) {
                splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
            }
            splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
            lastIndex = matcher.end();
        }
        if (lastIndex != targetStr.length()) {
            splitTextList.add(targetStr.substring(lastIndex, targetStr.length()));
        }
        return splitTextList;
    }

    /**
     * 清除html不包括<br/>
     *
     * @param clearContent
     * @return
     */
    public static String cleanHtmlTag(String clearContent) {
        String content = clearContent.replaceAll("</p>|(<br>|(<br(.*?)/>)|<BR>|<BR/>)","_br1g2br_");
        return Jsoup.clean(content, new Whitelist()).replaceAll("_br1g2br_", "<br/>");
    }
}
